package com.eqdd.yiqidian.ui.mine.qiye;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.eqdd.nextinputs.Scheme;
import com.eqdd.nextinputs.StaticScheme;
import com.eqdd.nextinputs.ValueScheme;
import com.eqdd.yiqidian.QiyeRegisterActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.AreaBean;
import com.eqdd.yiqidian.bean.EditBean;
import com.eqdd.yiqidian.bean.choose.HangyeBean;
import com.eqdd.yiqidian.bean.utils.MultiChooseBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.service.UserService;
import com.eqdd.yiqidian.ui.base.BaseMultiEditActivity;
import com.eqdd.yiqidian.utils.MultiChooseTestUtil;
import com.eqdd.yiqidian.utils.SPUtil;
import com.eqdd.yiqidian.utils.SingleChooseUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.eqdd.yiqidian.widget.EditDialogFragment;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;

import java.util.ArrayList;
import java.util.List;

import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.ISelectAble;
import io.reactivex.Flowable;
import io.rong.imkit.plugin.location.AMapLocationInfo;
import io.rong.imkit.plugin.location.IMyLocationChangedListener;
import io.rong.imkit.plugin.location.LocationManager;
import io.rong.imlib.model.Conversation;

public class QiyeRegisterActivity extends BaseMultiEditActivity implements IMyLocationChangedListener {
    private QiyeRegisterActivityCustom dataBinding;
    private String[] titles = new String[]{
            "企业名称",
            "法定代表人/企业负责人姓名",
            "法定代表人/企业负责人身份证号",
            "法定代表人/企业负责人手机号码",
            "企业类型",
            "所在行业",
            "公司所在地",
            "企业联系电话（座机）",
            "企业邮箱"
    };
    private String[] titleTexts = new String[]{
            "企业名称",
            "法定代表人/企业负责人姓名",
            "法定代表人/企业负责人身份证号",
            "法定代表人/企业负责人手机号码",
            null,
            null,
            "公司所在地",
            "企业联系电话（座机）",
            "企业邮箱"
    };
    private String[] tipTexts = new String[]{
            "企业名称",
            "法定代表人/企业负责人姓名",
            "法定代表人/企业负责人身份证号",
            "法定代表人/企业负责人手机号码",
            null,
            null,
            "公司所在地",
            "企业联系电话（座机）",
            "企业邮箱"
    };
    private int[] types = new int[]{
            0, 0, 0, 0, 4, 4, 4, 0, 0
    };
    private List<HangyeBean> hangyeBean;
    private BottomDialog dialog;
    private String location;
    private String phone;
    private BottomDialog hangyeDialog;
    private List<Scheme> schemes;
    private ActionSheetDialog leixingDialog;
    private List<AreaBean> areaBean;
    private BottomDialog areaDialog;
    private String result;
    private String quhao;
    private String guid;
    private String province;
    private String city;
    private String area;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_qiye_register);
        initTopTitleBar(View.VISIBLE, "企业注册");
        initTopRightText("提交", (v) -> {
            if (checkParam()) {
                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.QIYE_REGISTER)
                        .params("userGuid", guid)
                        .params("name", editBeans.get(0).getContent())
                        .params("dutyman", editBeans.get(1).getContent())
                        .params("dutyIDnum", editBeans.get(2).getContent())
                        .params("dutytel", editBeans.get(3).getContent())
                        .params("type", editBeans.get(4).getContent())
                        .params("hangye", editBeans.get(5).getContent())
                        .params("address", editBeans.get(6).getContent())
                        .params("contact", editBeans.get(7).getContent())
                        .params("email", editBeans.get(8).getContent())
                        .params("quhao", quhao)
                        .params("province", province)
                        .params("city", city)
                        .params("area", area)
                        .params("hangyehao", editBeans.get(5).getContent().substring(editBeans.get(5).getContent().lastIndexOf("-") + 1, editBeans.get(5).getContent().length()))
                        .execute(new DialogCallBack<HttpResult>(this) {
                            @Override
                            public void onSuccess(Response<HttpResult> response) {
                                HttpResult httpResult = response.body();
                                ToastUtil.showShort(httpResult.getMsg());
                                if (httpResult.getStatus() == 200) {
                                    clearData();
                                    isSaveData = false;
                                    startService(new Intent(QiyeRegisterActivity.this, UserService.class));
                                    finish();
                                }
                            }
                        });
            } else {
                ToastUtil.showShort("请先完善你信息");
            }
        });
    }

    private boolean checkParam() {
        for (int i = 0; i < quickAdapter.getData().size(); i++) {
            if (TextUtils.isEmpty(quickAdapter.getItem(i).getContent())) {
                return false;
            }
        }
        return true;
    }


    @Override
    public void initData() {
        phone = getIntent().getStringExtra("phone");
        guid = getIntent().getStringExtra(Config.GUID);
        if (AppConstent.user != null) {
            phone = AppConstent.user.getUname();
            guid = AppConstent.user.getGuid();
        }
        getHttpData();
        if (user != null) {
            System.out.println("user不为空，获取地理位置");
            LocationManager.getInstance().bindConversation(this, Conversation.ConversationType.PRIVATE, user.getGuid());
            LocationManager.getInstance().setMyLocationChangedListener(this);
            LocationManager.getInstance().updateMyLocation();
        }
        for (int i = 0; i < titles.length; i++) {
            EditBean editBean = new EditBean();
            editBean.setTitle(titles[i]);
            editBean.setType(types[i]);
            editBean.setContent("");
            editBean.setTextTip(tipTexts[i]);
            editBean.setTextTitle(titleTexts[i]);
            switch (i) {
                case 2:
                    schemes = new ArrayList<>();
                    schemes.add(ValueScheme.Required());
                    schemes.add(StaticScheme.ChineseIDCard());
                    editBean.setSchemes(schemes);
                    break;
                case 3:
                    schemes = new ArrayList<>();
                    schemes.add(ValueScheme.Required());
                    schemes.add(StaticScheme.ChineseMobile());
                    editBean.setSchemes(schemes);
                    break;
                case 6:
                    if (!TextUtils.isEmpty(location)) {
                        editBean.setContent(location);
                    }
                    break;
                case 7:
                    schemes = new ArrayList<>();
                    schemes.add(ValueScheme.Required());
                    schemes.add(StaticScheme.ChineseTelephone());
                    editBean.setSchemes(schemes);
                    break;
                case 8:
                    schemes = new ArrayList<>();
                    schemes.add(ValueScheme.Required());
                    schemes.add(StaticScheme.Email());
                    editBean.setSchemes(schemes);
                    break;
            }
            editBeans.add(editBean);
        }
    }


    private void getHttpData() {
        showLoading();
        Flowable<List<AreaBean>> areaFlow = OkGo.<List<AreaBean>>get(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                .params("type", 0)
//                .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + "0")
//                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                .converter(new JsonConverter<List<AreaBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<List<AreaBean>>());
        Flowable<List<HangyeBean>> hangyeFlow = OkGo.<List<HangyeBean>>get(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                .params("type", 2)
//                .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + "2")
//                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                .converter(new JsonConverter<List<HangyeBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<List<HangyeBean>>());

        Flowable.combineLatest(areaFlow, hangyeFlow, (s, s2) -> {
                    areaBean = s;
                    hangyeBean = s2;
                    return 1;
                }
        ).subscribe(o -> {
                    initHangyePicker();
                    initAreaPicker();
                }
                , e -> {
                    hideLoading();
                    System.out.println(e.toString());
                    ToastUtil.showShort(Config.SERVER_ERROR);
                }, () -> {
                    hideLoading();
                });
    }

    private void initHangyePicker() {
        List<MultiChooseBean> multiChooseBeen = new ArrayList<>();
        multiChooseBeen.addAll(hangyeBean);
        hangyeDialog = new MultiChooseTestUtil().getAreaDialog(QiyeRegisterActivity.this, 3, multiChooseBeen, (d, a) -> {
            hangyeDialog.dismiss();
            String result = "";
            for (ISelectAble iSelectAble : a) {
                result += iSelectAble.getName();
            }
            editBeans.get(5).setContent(a.get(2).getName() + "-" + ((HangyeBean) (a.get(2).getArg())).getCode());
            quickAdapter.notifyItemChanged(5);

        });
    }

    private void initAreaPicker() {
        List<MultiChooseBean> multiChooseBeen = new ArrayList<>();
        multiChooseBeen.addAll(areaBean);
        areaDialog = new MultiChooseTestUtil().getAreaDialog(QiyeRegisterActivity.this, 3, multiChooseBeen, (d, a) -> {
            areaDialog.dismiss();
            result = "";
            for (ISelectAble iSelectAble : a) {
                result += iSelectAble.getName();
            }
            province = a.get(0).getName();
            city = a.get(1).getName();
            area = a.get(2).getName();
            if (((AreaBean) a.get(1).getArg()).getCode().equals("0")) {
                quhao = ((AreaBean) a.get(2).getArg()).getQucode();
            } else {
                quhao = ((AreaBean) a.get(1).getArg()).getCode();
            }
            editBeans.get(6).setContent(result);
            quickAdapter.notifyItemChanged(6);
            EditDialogFragment editDiglog = ChooseAlertView.getEditDiglog("请输入详细地址", "详细地址", null, contents -> {
                editBeans.get(6).setContent(result + contents.get(0));
                quickAdapter.notifyItemChanged(6);
            });
            editDiglog.show(getSupportFragmentManager(), "edit");

        });
    }

    @Override
    protected RecyclerView initRecyclerView() {
        return dataBinding.recyclerView;
    }

    @Override
    public void itemClick(int p) {

        if (p == 5) {
            hangyeDialog.show();
        } else if (p == 6) {
            areaDialog.show();
        } else if (p == 4) {
            if (leixingDialog == null) {
                SingleChooseUtil.getChooseDialog(this, 6,
                        sheetDialog -> {
                            leixingDialog = sheetDialog;
                            leixingDialog.show();
                        }
                        , (position, strings) -> {
                            quickAdapter.getItem(4).setContent(strings.get(position - 1));
                            quickAdapter.notifyItemChanged(4);
                        }

                );
            } else {
                leixingDialog.show();
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    public void onMyLocationChanged(AMapLocationInfo aMapLocationInfo) {
        if (aMapLocationInfo != null) {
            location = aMapLocationInfo.getProvince()
                    + aMapLocationInfo.getCity()
                    + aMapLocationInfo.getDistrict() + "-"
                    + aMapLocationInfo.getCitycode();
            if (quickAdapter != null && editBeans.size() > 0) {
                editBeans.get(6).setContent(location);
                quickAdapter.notifyItemChanged(6);
            }
            System.out.println(location);
        }
    }

    @Override
    public void saveData() {
        if (editBeans != null) {
            SPUtil.setParam(getLocalClassName() + phone, editBeans);
        }
        if (!TextUtils.isEmpty(quhao)) {
            SPUtil.setParam(getLocalClassName() + phone + "quhao", quhao);
        }
    }

    @Override
    public void recoverData() {
        List<EditBean> datas = (List<EditBean>) SPUtil.getParam(getLocalClassName() + phone);
        if (datas != null) {
            editBeans = datas;
        }
        String data = (String) SPUtil.getParam(getLocalClassName() + phone + "quhao", Config.NULL);
        if (data != Config.NULL) {
            quhao = data;
        }
    }

    @Override
    public void clearData() {
        SPUtil.setParam(getLocalClassName() + phone, Config.NULL);
        SPUtil.setParam(getLocalClassName() + phone + "quhao", Config.NULL);

    }
}
